package com.army.study.service;

import com.army.study.database.DatabaseUtils;
import com.army.study.database.FormDatabase;
import com.army.study.database.Form;
import com.army.study.database.Sensor;
import com.army.study.slice.MainAbilitySlice;
import com.army.study.utils.ChartDataUtils;
import com.army.study.utils.DateUtils;
import com.army.study.utils.LogUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.FormBindingData;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.content.Intent;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.sensor.agent.CategoryMotionAgent;
import ohos.sensor.bean.CategoryMotion;
import ohos.sensor.data.CategoryMotionData;
import ohos.sensor.listener.ICategoryMotionDataCallback;
import ohos.utils.zson.ZSONObject;

import java.util.List;

/**
 * 计步器传感器Service
 */
public class StepSensorService extends Ability {
    private static final long INTERVAL = 100000000L;
    private CategoryMotionAgent categoryMotionAgent = new CategoryMotionAgent();
    private ICategoryMotionDataCallback categoryMotionDataCallback;
    private CategoryMotion categoryMotion;
    private StepSensorService.MyEventHandler myEventHandler;
    private DatabaseHelper helper = new DatabaseHelper(this);
    private OrmContext connect;


    @Override
    protected void onStart(Intent intent) {
        LogUtils.info("ArmyService", "StepSensorService::onStart");
        LogUtils.debug("ArmyService", "StepSensorService::onStart");
        super.onStart(intent);

        connect = helper.getOrmContext("FormDatabase", "FormDatabase.db", FormDatabase.class);
        myEventHandler = new MyEventHandler(EventRunner.getMainEventRunner());

        categoryMotionDataCallback = new ICategoryMotionDataCallback() {
            @Override
            public void onSensorDataModified(CategoryMotionData categoryMotionData) {
                float[] values = categoryMotionData.getValues();
                handleSensorData(values[0]);
            }

            @Override
            public void onAccuracyDataModified(CategoryMotion categoryMotion, int i) {
            }

            @Override
            public void onCommandCompleted(CategoryMotion categoryMotion) {
            }
        };

        // 获取计步器对象
        categoryMotion = categoryMotionAgent.getSingleSensor(CategoryMotion.SENSOR_TYPE_PEDOMETER);
        if (categoryMotion != null) {
            // 设置传感器数据回调
            categoryMotionAgent.setSensorDataCallback(categoryMotionDataCallback, categoryMotion, INTERVAL);
        }
    }

    private void handleSensorData(float value) {
        // 0为今天日期, 1为昨天日期
        Sensor realSensor = DatabaseUtils.getRealSensorData(value, connect, DateUtils.getDate(0), DateUtils.getDate(1));
        float realValue = realSensor.getStepsValue();
        String stringValue = String.valueOf((int)realValue);
        myEventHandler.postTask(new Runnable() {
            @Override
            public void run() {
                // 存储数据
                DatabaseUtils.insertValues(realValue, connect);
                // 更新页面
                MainAbilitySlice.updatePage(stringValue);
                // 更新卡片
                updateForms(stringValue);
            }
        });
    }

    private void updateForms(String value) {
        OrmPredicates ormPredicates = new OrmPredicates(Form.class);
        List<Form> forms = connect.query(ormPredicates);
        if (forms.size() < 1) {
            return;
        }
        for (Form form : forms) {
            ZSONObject result = ChartDataUtils.getZSONObject(value, form.getDimension(), connect);
            try {
                updateForm(form.getFormId(), new FormBindingData(result));
            } catch (FormException e) {
                connect.delete(form);
                LogUtils.error("updateForms", "formId not exit");
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        categoryMotionAgent.releaseSensorDataCallback(categoryMotionDataCallback);
        LogUtils.info("Service", "StepSensorService::onStop");
    }

    @Override
    protected void onBackground() {
        super.onBackground();
        LogUtils.info("Service", "StepSensorService::onBackground");
    }

    @Override
    protected void onDisconnect(Intent intent) {
        super.onDisconnect(intent);
    }

    /**
     * 用于线程间的通信
     */
    class MyEventHandler extends EventHandler {

        MyEventHandler(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
        }
    }
}
